import { ref } from "vue"
/* 点击点的经纬度 */
const mylnglat = ref("")
/* 标志是否在地图上点点的变量，false的时候是没有点点 */
var flag = ref(false)

/* 地图的变量 */
var map = null
/* 光谷数字化地图的变量 */
var docLayer = null
/* 添加画布 */
var source = null
var layer = null
/* 画笔 */
var draw = null

export const initMap = ({ ruleForm, arr, attr, service }) => {
  map = new ol.Map({
    target: "map",
    layers: [TianDiMap_img, TianDiMap_cia, TianDiMap_vec, TiandiMap_cva],
    view: new ol.View({
      center: [114.38, 30.49],
      zoom: 13,
      projection: "EPSG:4326",
    }),
  })
  docLayer = new Zondy.Map.Doc("", "traffic", {
    ip: "localhost",
    port: 6163,
  })
  source = new ol.source.Vector({})
  layer = new ol.layer.Vector({
    source,
    style: new ol.style.Style({
      image: new ol.style.Circle({
        radius: 10,
        fill: new ol.style.Fill({
          color: "rgba(255,255,255,0.5)",
        }),
        stroke: new ol.style.Stroke({
          color: "#1fffff",
          width: 2,
        }),
      }),
    }),
  })
  map.addLayer(layer)
  map.addLayer(docLayer)

  function handleAdd() {
    /* 先将标志变量改回去，再清空上一次的标记点 */
    flag.value = false
    source.clear()
    draw = new ol.interaction.Draw({
      source,
      type: "Point",
      style: new ol.style.Style({
        image: new ol.style.Circle({
          radius: 10,
          fill: new ol.style.Fill({
            color: "rgba(255,255,255,0.5)",
          }),
          stroke: new ol.style.Stroke({
            color: "#1fffff",
            width: 2,
          }),
        }),
      }),
    })
    map.addInteraction(draw)
    draw.on("drawend", function (evt) {
      //console.log(evt.target.sketchCoords_)
      mylnglat.value = evt.target.sketchCoords_.join(",")
      ruleForm.lnglat = mylnglat
      //console.log(mylnglat.value)
      // console.log(typeof mylnglat)
      // /* 如果点了一个点，点了之后就销毁画笔
      if (mylnglat) {
        flag.value = true
        map.removeInteraction(draw)
      }
    })
  }

  /* 在这里写向空间数据库添加点的函数 */
  function handleAddPoint(arr, attr, service) {
    layer = new ol.layer.Vector({
      source,
      style: new ol.style.Style({
        image: new ol.style.Circle({
          radius: 10,
          fill: new ol.style.Fill({
            color: "rgba(255,255,255,0.5)",
          }),
          stroke: new ol.style.Stroke({
            color: "#1fffff",
            width: 2,
          }),
        }),
      }),
    })
    draw = createDraw({
      source,
      callback: handleDraw(arr, attr, service),
    })
    map.addInteraction(draw)
  }
  /* 添加事件点的回调函数 */
  function handleDraw(arr, attr, service) {
    /* source.clear() */
    Point.addEvent({
      position: arr,
      attr,
      service,
      docName: docLayer,
    })
    map.removeInteraction(draw)
  }

  return { handleAdd, flag, mylnglat, handleAddPoint }
}
